/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package session01.module01.three_layer.dal;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import session01.module01.three_layer.entities.Classes;

/**
 *
 * @author sinhnx <sinhnx@fpt.aptech.ac.vn>
 */
public class ClassesDAO {

    private Connection cn;
    private String sql;
    private PreparedStatement pstm;

    public ClassesDAO() {
        cn = DB_Util.getConnection();
    }

    public ClassesDAO(Connection cn) {
        this.cn = cn;
    }
    
    public Classes getByClassName(String className){
        sql = "SELECT ClassName, Location FROM Classes WHERE ClassName=?";
        if (cn == null) {
            return null;
        }
        ResultSet rs = null;
        try {
            pstm = cn.prepareStatement(sql);
            pstm.setString(1, className);
            rs = pstm.executeQuery();
            if(rs.next()){
                return new Classes(className, rs.getString("Location"));
            }
        } catch (SQLException ex) {
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException ex) {
                Logger.getLogger(ClassesDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return null;
    }

    private List<Classes> convert2Entity(ResultSet rs) throws SQLException {
        if (rs == null) {
            return null;
        }
        List<Classes> list = new ArrayList();
        while (rs.next()) {
            list.add(new Classes(rs.getString("ClassName"), rs.getString("Location")));
        }
        return list;
    }

    public List<Classes> getAll() {
        sql = "SELECT ClassName, Location FROM Classes ORDER BY Location";
        if (cn == null) {
            return null;
        }
        ResultSet rs = null;
        try {
            rs = cn.createStatement().executeQuery(sql);
            return convert2Entity(rs);
        } catch (SQLException ex) {
            return null;
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
            } catch (SQLException ex) {
                Logger.getLogger(ClassesDAO.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}
